package com.ywj.apacheFTP;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;

public class FTPUtils {

    private static FTPClient ftpClient;          //创建对象
    private static String ip = "192.168.0.1";    //ftp服务器地址
    private static Integer port = 21;            //ftp服务端默认端口号是21
    private static String userName = "ywj";   //ftp用户名
    private static String passWord = "root";	 //ftp登录密码



    /**
     * 初始化ftp服务器
     */
    public static boolean initFtpClient(){
        boolean is_success = false;
        int reply;
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip, port);			//连接Ftp服务器
            ftpClient.login(userName, passWord);  //登陆Ftp服务器
            ftpClient.setControlEncoding("utf-8");//设置编码类型
            reply = ftpClient.getReplyCode();     //获取返回码，用于判断是否连接成功
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new Exception("服务器连接失败");
            } else {
                ftpClient.enterLocalPassiveMode();  //设置被动模式
                ftpClient.setControlEncoding("GBK");//设置字符模式，解决中文乱码问题
                is_success = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return is_success;
    }

    /**
     * 关闭连接
     */
    public static void dropFtpClient() {
        try {
            ftpClient.logout();     //退出登陆
            if (ftpClient.isConnected()) {//检测是否连接Ftp服务器
                ftpClient.disconnect(); //关闭连接
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param pathname       ftp服务保存地址
     * @param originfilename 待上传文件的名称（绝对地址） *
     * @return
     */
    public static boolean uploadFile(String pathname, String originfilename) {
        boolean is_success = false;
        InputStream inputStream = null;
        try {
            File localFile = new File(originfilename);
            inputStream = new FileInputStream(localFile);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.changeWorkingDirectory(pathname); //跳转到指定的Ftp文件目录（相对路径）
            is_success = ftpClient.storeFile(localFile.getName(), inputStream);//上传文件
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return is_success;
    }


    /**
     * 下载文件
     *
     * @param pathName   ftp服务器文件目录
     * @param localPath  下载后的文件路径
     * @return
     */
    public static boolean downloadFile(String pathName, String localPath) {
        boolean is_success = false;
        OutputStream os = null;
        try {
            ftpClient.changeWorkingDirectory(pathName);//跳转到指定的Ftp文件目录
            FTPFile[] ftpFiles = ftpClient.listFiles();//获取目录下所有的文件和文件夹
            //遍历目录下所有的文件
            for (FTPFile file : ftpFiles) {
                if (file.isFile()) {
                    File localFile = new File(localPath + "/" + file.getName());
                    os = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(file.getName(), os);//下载文件到本地
                    os.close();
                } else if (file.isDirectory()) {
                    downloadFile(pathName + file.getName() + "/", localPath);
                }
            }
            is_success = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return is_success;
    }

    /*
     * 删除文件
     *
     * @param pathName  ftp服务器文件目录
     * @param fileName  删除的文件名
     * @return
     */
    public static boolean deleteFile(String pathNmae, String fileName) {
        boolean is_success = false;
        try {
            ftpClient.changeWorkingDirectory(pathNmae);
            is_success = ftpClient.deleteFile(fileName);//删除文件
        } catch (Exception e) {
            e.printStackTrace();
        }
        return is_success;
    }



    /*
    /**
     * 删除文件 *
     *
     * @param pathname FTP服务器保存目录 *
     * @param filename 要删除的文件名称 *
     * @return
     */
    /*
    public boolean deleteFile(String pathname, String filename) {
        boolean is_success = false;
        try {
            initFtpClient();
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.dele(filename);
            ftpClient.logout();
            is_success = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return is_success;
    }
    */


    //改变目录路径
    public boolean changeWorkingDirectory(String directory) {
        boolean flag = true;
        try {
            flag = ftpClient.changeWorkingDirectory(directory);
            if (flag) {
                System.out.println("进入文件夹" + directory + " 成功！");

            } else {
                System.out.println("进入文件夹" + directory + " 失败！开始创建文件夹");
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return flag;
    }

    //创建多层目录文件，如果有ftp服务器已存在该文件，则不创建，如果无，则创建
    public boolean createDirecroty(String remote) throws IOException {
        String directory = remote + "/";
        // 如果远程目录不存在，则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(directory)) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            }
            end = directory.indexOf("/", start);
            String path = "";
            StringBuilder paths = new StringBuilder();
            while (true) {
                String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                path = path + "/" + subDirectory;
                if (!existFile(path)) {
                    if (makeDirectory(subDirectory)) {
                        changeWorkingDirectory(subDirectory);
                    } else {
                        System.out.println("创建目录[" + subDirectory + "]失败");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    changeWorkingDirectory(subDirectory);
                }
                paths.append("/").append(subDirectory);
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return true;
    }

    //判断ftp服务器文件是否存在
    public boolean existFile(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }

    //创建目录
    public boolean makeDirectory(String dir) {
        boolean flag = true;
        try {
            flag = ftpClient.makeDirectory(dir);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    public static void main(String[] arg) throws Exception {
        boolean is_success = false;
        //初始化FtpClient
        is_success = initFtpClient();
        System.out.println(is_success);
        //下载Ftp上的所有文件到本地
        is_success=downloadFile("/","D:\\test0");
        System.out.println(is_success);
        //删除Ftp上指定文件
        is_success = deleteFile("/", "1.jpg");
        System.out.println(is_success);
        //将本地文件上传到Ftp服务器
        is_success = uploadFile("/","D:\\test0\\1.jpg");

        System.out.println(is_success);
        //退出登陆、关闭连接
        dropFtpClient();
    }



}



